package io.renren.utils.httpclient;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.renren.entity.User;
 
public class HttpRequestUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);    //日志记录
    
    public static String filePath = "/imsyncdataconf.properties";
    
    //同步失败信息
    private static String errMsg = "同步操作失败，请重试!";
    
    private static String succProperty = "status";
    private static String retSuccess = "success";
    /**
     * httpPost
     * @param url  路径
     * @param obj  对象
     * @return
     */
    public static JSONObject httpPost(String url,Object obj){
        return httpPost(url, obj, true);
    }
    
    /**
     * httpPut
     * @param url  路径
     * @param obj  对象
     * @return
     */
    public static JSONObject httpPut(String url,Object obj){
        return httpPut(url, obj, true);
    }
    
    /**
     * post请求
     * @param url         url地址
     * @param obj         对象
     * @param noNeedResponse    不需要返回结果
     * @return
     */
    public static JSONObject httpPost(String url,Object obj, boolean noNeedResponse){
    	if(url == null || !url.contains("http")){
    		return null;
    	}
        //post请求返回结果
    	JSONObject jsonParam = JSONObject.fromObject(obj, getJsonConfig());
        JSONObject jsonResult = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        setHeaders(post);
        try {
            if (null != jsonParam) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                post.setEntity(entity);
            }
            CloseableHttpResponse  result = httpClient.execute(post);
            url = URLDecoder.decode(url, "UTF-8");
            /**读取服务器返回过来的json字符串数据**/
        	String str = EntityUtils.toString(result.getEntity());
            jsonResult = JSONObject.fromObject(str);
            /**请求发送成功，并得到响应**/
            if (!(result.getStatusLine().getStatusCode() == HttpStatus.SC_OK && retSuccess.equals(jsonResult.getString(succProperty)))) {
            	 String message=	(String) jsonResult.get("message");
             	throw new BizException(message);
            }
        } catch (IOException e) {
        	logger.error("post请求失败 : "+url,e);
        	 String message=	(String) jsonResult.get("message");
         	throw new BizException(message);
        }finally{
        	 post.completed();
        }
        return jsonResult;
    }
 
    /**
     * put请求
     * @param url         url地址
     * @param obj         对象
     * @param noNeedResponse    不需要返回结果
     * @return
     */
    public static JSONObject httpPut(String url,Object obj, boolean noNeedResponse){
    	if(url == null || !url.contains("http")){
    		return null;
    	}
        //post请求返回结果
    	JSONObject jsonParam = JSONObject.fromObject(obj, getJsonConfig());
        JSONObject jsonResult = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut put = new HttpPut(url);
        setHeaders(put);
        try {
            if (null != jsonParam) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                put.setEntity(entity);
            }
            CloseableHttpResponse  result = httpClient.execute(put);
            url = URLDecoder.decode(url, "UTF-8");
            /**读取服务器返回过来的json字符串数据**/
        	String str = EntityUtils.toString(result.getEntity());
            jsonResult = JSONObject.fromObject(str);
            /**请求发送成功，并得到响应**/
            if (!(result.getStatusLine().getStatusCode() == HttpStatus.SC_OK && retSuccess.equals(jsonResult.getString(succProperty)))) {
            String message=	(String) jsonResult.get("message");
            	throw new BizException(message);
            }
        } catch (IOException e) {
        	logger.error("put请求失败 : "+url,e);
         String message=	(String) jsonResult.get("message");
         	throw new BizException(message);
        }finally{
        	put.completed();
        }
        return jsonResult;
    }
 
    /**
     * 发送get请求
     * @param url    路径
     * @return
     */
    public static JSONObject httpGet(String url){
    	if(url == null || !url.contains("http")){
    		return null;
    	}
        //get请求返回结果
        JSONObject jsonResult = null;
        //发送get请求
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        setHeaders(get);
        try {
            CloseableHttpResponse result = client.execute(get);
            /**请求发送成功，并得到响应**/
            String strResult = EntityUtils.toString(result.getEntity());
            jsonResult = JSONObject.fromObject(strResult);
            url = URLDecoder.decode(url, "UTF-8");
            if (!(result.getStatusLine().getStatusCode() == HttpStatus.SC_OK && retSuccess.equals(jsonResult.getString(succProperty)))) {
            	 String message=	(String) jsonResult.get("message");
             	throw new BizException(message);
            }
        } catch (IOException e) {
        	logger.error("get请求失败 : "+url,e);
        	 String message=	(String) jsonResult.get("message");
         	throw new BizException(message);
        }finally{
        	 get.completed();
        }
        return jsonResult;
    }
    
    
    public static JSONObject httpGetToYkb(String url){
    	if(url == null || !url.contains("http")){
    		return null;
    	}
        //get请求返回结果
        JSONObject jsonResult = null;
        //发送get请求
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        setHeaders(get);
        try {
            CloseableHttpResponse result = client.execute(get);
            /**请求发送成功，并得到响应**/
            String strResult = EntityUtils.toString(result.getEntity());
            jsonResult = JSONObject.fromObject(strResult);
            url = URLDecoder.decode(url, "UTF-8");
        } catch (IOException e) {
        	logger.error("get请求失败 : "+url,e);
        	 String message=	(String) jsonResult.get("message");
         	throw new BizException(message);
        }finally{
        	 get.completed();
        }
        return jsonResult;
    }
    
    /**
     * 发送delete 请求
     * @param url    路径
     * @return
     */
    public static JSONObject httpDelete(String url){
    	if(url == null || !url.contains("http")){
    		return null;
    	}
        //get请求返回结果
        JSONObject jsonResult = null;
        //发送get请求
        CloseableHttpClient client = HttpClients.createDefault();
        HttpDelete httpdel = new HttpDelete(url);
        setHeaders(httpdel);
        try {
        	CloseableHttpResponse result = client.execute(httpdel);
            /**请求发送成功，并得到响应**/
            String strResult = EntityUtils.toString(result.getEntity());
            jsonResult = JSONObject.fromObject(strResult);
            url = URLDecoder.decode(url, "UTF-8");
            if (!(result.getStatusLine().getStatusCode() == HttpStatus.SC_OK && retSuccess.equals(jsonResult.getString(succProperty)))) {
            	 String message=	(String) jsonResult.get("message");
             	throw new BizException(message);
            }
        } catch (IOException e) {
        	logger.error("delete请求失败 : "+url,e);
        	 String message=	(String) jsonResult.get("message");
         	throw new BizException(message);
        }finally{
        	 httpdel.completed();
        }
        return jsonResult;
    }
    
    
    public static Properties loadPropertiesFile(String filePath){
    	Properties prop = null;
    	try{
	    	InputStream in = HttpRequestUtils.class.getResourceAsStream(filePath);
	    	prop = new Properties();
	    	prop.load(in);
    	}catch(Exception e){
    	}
    	return prop;
    }
    
    public static String getUrl(String className){
    	Properties pro = loadPropertiesFile(filePath);
    	if(pro==null){
    		return "";
    	}
		String dosync = pro.getProperty("dosync");
		if("1".equals(dosync)){
			String url = pro.getProperty("url");
		    return url+className.toLowerCase();
		}else{
			return "";
		}
    }
    
    private static void setHeaders(HttpRequestBase base){
    	base.addHeader("Accept", "*/*");
    	base.addHeader("Accept-Encoding", "gzip, deflate");
    	base.addHeader("Accept-Language", "zh-CN,zh;q=0.8");
    	base.addHeader("Connection", "keep-alive");
    	base.addHeader("Content-Type", "application/json;charset=UTF-8");
    	base.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.22 Safari/537.36 SE 2.X MetaSr 1.0");
    //	base.addHeader("userId", SysContent.getUserId());
    //	base.addHeader("corpId", SysContent.getCorpId());
    }
    
    public static JsonConfig getJsonConfig(){
    	JsonConfig jsonConfig = new JsonConfig();  
		PropertyFilter filter = new PropertyFilter() {
            @SuppressWarnings("unchecked")
			public boolean apply(Object object, String fieldName, Object fieldValue) {
                if(fieldValue instanceof List){
                    List<Object> list = (List<Object>) fieldValue;
                    if (list.size()==0) {
                        return true;
                    }
                }
                if(fieldName.endsWith("String")){
                	return true;
                }
                return null == fieldValue || "".equals(fieldValue);
            }
		};
		jsonConfig.setJsonPropertyFilter(filter);
		jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
		return jsonConfig;
    }
    
    public static JSONObject pinkUrl(String ip,String module ,String able,Object object){
    	JSONObject jSONObject =  null;
    	String url = "http://";
    	url = url+ ip+"/cloudfi/"+module;
    	switch (able) {
		case "add":
			jSONObject =	httpPut(url,object);
			break;
		case "del":
			url = url+"/"+object.toString();
			jSONObject=httpDelete(url);
			break;
		case "update":
			url = url+"/"+((User)object).getId();
			jSONObject=	httpPost(url, object);
			break;
		case "select":
			jSONObject=	httpPost(url, object);
			break;
		case "batchdelete" :
			jSONObject=	httpPost(url, object);
			break;
		default:
			break;
		}
    	return jSONObject;
    } 
}